/**
 * Created by donggaina on 2019/1/22.
 */
$(function () {
    var tmpl = '<li class="weui-uploader__file" style="background-image:url(#url#)"></li>',
        $gallery = $("#gallery"), $galleryImg = $("#galleryImg"),
        $uploaderInput = $("#uploaderInput"),
        $uploaderFiles = $("ul.weui-uploader__files")

    ;
    $uploaderFiles.on("click", "li", function () {
        $galleryImg.attr("style", $(this).attr("style"));
        $gallery.fadeIn(100);
    });
    $gallery.on("click", function () {
        $gallery.fadeOut(100);
    });
    function helpMessage(message) {
        $(".helpMsg").text(message).fadeIn(200);
        setTimeout(function () {
            $(".helpMsg").fadeOut(200);
        }, 2000);
    }
    var concatStr = function (str1, str2) {
        var arr = [];
        arr.push(str1);
        arr.push(str2);
        return arr.join();
    };
    function getUploadToken() {
        var token = ""
        $.ajax({
            type: "POST",
            url: "/attachments/getUploadToken2",
            async: false,
            success: function (data) {
                if (data.status == "success") {
                    token = data.token;
                    console.log("getUploadToken success.");
                }
            },
        });
        return token
    }
    function getRandom(length) {
        var str = Math.random().toString(36).substr(2);
        if (str.length >= length) {
            return str.substr(0, length);
        }
        str += getRandom(length - str.length);
        return str;
    }
    var Qiniu_upload = function (f, token, key, name) {
        var Qiniu_UploadUrl = "https://upload-z1.qiniup.com";
        var xhr = new XMLHttpRequest();
        xhr.open('POST', Qiniu_UploadUrl, true);
        var formData = new FormData();
        formData.append('key', key);
        formData.append('token', token);
        formData.append('file', f);
        xhr.onreadystatechange = function (response) {
            if (xhr.readyState == 4 && xhr.status == 200 && xhr.responseText != "") {
                // var blkRet = JSON.parse(xhr.responseText);
                var blkRet = JSON.parse(xhr.responseText);
                if (blkRet.key)
                {
                    $("#" + name + "UploaderFiles").append($(tmpl.replace('#url#', "https://quickloanfs.cindata.cn/" + blkRet.key)));
                }
                var attachmentUrlStr = concatStr($("#" + name + "Url").val(), blkRet.key)
                $("#" + name + "Url").val(attachmentUrlStr);
                console.log("name2:"+ $("#" + name + "Url").val())
            } else if (xhr.status != 200 && xhr.responseText) {
                var blkRet = JSON.parse(xhr.responseText);
                console.log(blkRet);
            }
        };
        xhr.send(formData);
    };


    $("input[type='file']").change(function (e) {
        fileUploadById($(this).attr("id"));
    })

    function fileUploadById(name) {
        var token = getUploadToken();
        var files =  $("#" + name)[0];
        for (var i = 0; i < files.files.length; i++) {
            var file = files.files[i];
            if (file.size > 1024 * 1024 * 5 + 100) {
                helpMessage("图片大于5M，请修改后上传");
                return;
            }
            var key = getRandom(28) + file.name.substr(file.name.lastIndexOf('.'))
            Qiniu_upload(file, token, key, name)
        }
    }



})